package com.it.utils;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    public static final String LOGIN_FAILED="/loginFailed";
    /**
     * 在请求之前执行
     * @param request
     * @param response
     * @param handler 表示被拦截的请求目标
     * @return false:拦截请求,终止请求 true:继续执行请求
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //业务逻辑代码编写...(如:解决乱码,权限验证)
        request.setCharacterEncoding("utf-8");
        System.out.println("拦截器-preHandle");

        //直接登录不拦截
        String uri = request.getRequestURI();
        if (uri.endsWith(LOGIN_FAILED) || uri.endsWith("login") || (uri.endsWith("loginIndex"))
                || (uri.endsWith("loginUser")) || (uri.endsWith("logout"))) {
            return true;
        }

        if(request != null && request.getSession() != null &&
                request.getSession().getAttribute("isLogin") != null && request.getSession().getAttribute("isLogin").toString().equals("true")){
            return true;
        }
        response.sendRedirect("/login");
        return false;
    }

    /**
     * @param modelAndView 可以对视图进行操作
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        //业务逻辑代码编写...(如:操作日志记录,更改视图信息)
        System.out.println("拦截器-postHandle");
    }

    /**
     * @param ex 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        //业务逻辑代码编写...(如:,资源销毁,异常处理)
        System.out.println("拦截器-afterCompletion");
    }
}